﻿using System;
using System.Web;
using SelArom.Net.Sitefinity.API.News;
using SelArom.Net.Sitefinity.API.Events;
using SelArom.Net.Sitefinity.Helpers;
using Newtonsoft.Json;

namespace SelArom.Net.Sitefinity.API
{
	/// <summary>
	/// HttpHandler for intercepting Sitefinity Toolkit API Requests
	/// </summary>
	public class APIHandler : IHttpHandler
	{
		private HttpRequest Request;
		private HttpResponse Response;

		protected EventsAPI eApi;
		protected NewsAPI nApi;

		/// <summary>
		/// You will need to configure this handler in the web.config file of your 
		/// web and register it with IIS before being able to use it. For more information
		/// see the following link: http://www.selarom.net
		/// </summary>
		#region IHttpHandler Members

		public bool IsReusable
		{
			// Return false in case your Managed Handler cannot be reused for another request.
			// Usually this would be false in case you have some state information preserved per request.
			get { return false; }
		}

		public void ProcessRequest(HttpContext context)
		{
			Request = context.Request;
			Response = context.Response;
			eApi = new EventsAPI();
			nApi = new NewsAPI();

			// init response
			Response.ContentType = "text/plain";
			var response = string.Empty;

			var url = Request.RawUrl.ToLower();
			if (url.Contains("externalmonthevents"))
				response = ExternalMonthEvents();
			else if (url.Contains("externaleventsbydate"))
				response = ExternalByDate();
			else if (url.Contains("monthevents"))
				response = MonthEvents();
			else if (url.Contains("eventsbydate"))
				response = EventsByDate();
			else if (url.Contains("latestnews"))
				response = LatestNews();
			else if (url.Contains("featurednews"))
				response = FeaturedNews();
			else
				response = "[]";

			Response.Write(response);
			Response.End();
		}

		#endregion

		#region Events
		#region LocalEvents
		/// <summary>
		/// Retrieves the events collected by day for a given month (passed by querystring) as a JSON string
		/// </summary>
		/// <returns>JSON string serialized with MonthEvents instance</returns>
		private string MonthEvents()
		{
			var m = Request.QueryString["month"];
			var y = Request.QueryString["year"];

			// init year
			int yr;
			if (!Int32.TryParse(y, out yr)) yr = DateTime.Now.Year;

			// init month
			int mon;
			if (!Int32.TryParse(m, out mon)) mon = DateTime.Now.Month;

			var month = eApi.MonthEvents(yr, mon);
			return JsonConvert.SerializeObject(month);
		}

		/// <summary>
		/// Retrieves events for a given date or date range (passed by querystring)
		/// </summary>
		/// <returns>JSON string serialized with EventList instance for given date/range</returns>
		private string EventsByDate()
		{
			// get requested date
			DateTime date;
			var d = Request.QueryString["date"];

			// return today by default
			if (!DateTime.TryParse(d, out date)) date = DateTime.Now; 
			return JsonConvert.SerializeObject(eApi.EventsByDate(date));
		}
		#endregion

		#region ExternalEvents
		/// <summary>
		/// Retrieves the externally flagged events collected by day for a given month (passed by querystring) as a JSON string
		/// </summary>
		/// <returns>JSON string serialized with MonthEvents instance</returns>
		public string ExternalMonthEvents()
		{
			// init year
			int yr;
			var y = Request.QueryString["year"];
			if (!Int32.TryParse(y, out yr)) yr = DateTime.Now.Year;

			// init month
			int mon;
			var m = Request.QueryString["month"];
			if (!Int32.TryParse(m, out mon)) mon = DateTime.Now.Month;

			var month = eApi.ExternalMonthEvents(yr, mon);
			return JsonConvert.SerializeObject(month);
		}

		/// <summary>
		/// Retrieves events for a given date or date range (passed by querystring)
		/// </summary>
		/// <returns>JSON string serialized with EventList instance for given date/range</returns>
		private string ExternalByDate()
		{
			// get requested date
			DateTime date;
			var d = Request.QueryString["date"];

			// retrieve today bv default
			if (!DateTime.TryParse(d, out date)) date = DateTime.Now;
			return JsonConvert.SerializeObject(eApi.ExternalEventsByDate(date));
		}
		#endregion
		#endregion

		#region News
		private string LatestNews()
		{
			var cat = Request.QueryString["category"];
			if (!string.IsNullOrEmpty(cat))
				return LatestNews(cat);

			var news = nApi.LatestNews();

			// TODO: replace lines below with this
			//int max;
			//if (Int32.TryParse(Request.QueryString["count"], out max) && news.Count > max)
			//    news.RemoveRange(max, news.Count - max);

			if (news.Count > 5)
				news.RemoveRange(5, news.Count - 5);

			return JsonConvert.SerializeObject(news);
		}

		private string LatestNews(string Category)
		{
			var news = nApi.LatestNews(Category);
			if (news.Count > 5)
				news.RemoveRange(5, news.Count - 5);

			return JsonConvert.SerializeObject(news);
		}

		private string FeaturedNews()
		{
			var news = nApi.FeaturedNews();
			if (news.Count > 5)
				news.RemoveRange(5, news.Count - 5);

			return JsonConvert.SerializeObject(news);
		}
		#endregion
	}
}